package com.anos.smsfun.task;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;

import com.anos.smsfun.controller.DataRequestCallback;
import com.anos.smsfun.controller.ThreadManager;
import com.anos.smsfun.model.ContactsWrapper;
import com.anos.smsfun.model.MessageItem;
import com.anos.smsfun.utility.Utils;

public class DoingBackground {

	/**
	 * TAST READ CONTACTS
	 * 
	 */
	public static void getContactList(
			final Context context,
			final DataRequestCallback<ArrayList<ContactsWrapper>> onDataListResults) {

		final ThreadManager atm = ThreadManager.getInstance(context);

		atm.execute(new Runnable() {

			final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
					Contacts._ID, // 0
					Contacts.DISPLAY_NAME, // 1
					Contacts.STARRED, // 2
					Contacts.TIMES_CONTACTED, // 3
					Contacts.CONTACT_PRESENCE, // 4
					Contacts.PHOTO_ID, // 5
					Contacts.LOOKUP_KEY, // 6
					Contacts.HAS_PHONE_NUMBER, // 7
			};

			private long contactId;
			private String display_name;
			private String phoneNumber;

			@Override
			public void run() {
				try {
					ArrayList<ContactsWrapper> contactsWrappers = new ArrayList<ContactsWrapper>();

					Uri uri = Contacts.CONTENT_URI;
					String select = "((" + Contacts.DISPLAY_NAME
							+ " NOTNULL) AND (" + Contacts.HAS_PHONE_NUMBER
							+ "=1) AND (" + Contacts.DISPLAY_NAME + " != '' ))";
					String sortOrder = Contacts.DISPLAY_NAME
							+ " COLLATE LOCALIZED ASC";

					Cursor c = context.getContentResolver().query(uri,
							CONTACTS_SUMMARY_PROJECTION, select, null,
							sortOrder);

					for (int i = 0; i < c.getCount(); i++) {
						try {
							c.moveToPosition(i);

							contactId = c.getLong(0);
							String hasPhone = c.getString(7);
							display_name = c.getString(1);
							phoneNumber = "";

							if (hasPhone.equalsIgnoreCase("1"))
								hasPhone = "true";
							else
								hasPhone = "false";

							if (Boolean.parseBoolean(hasPhone)) {
								Cursor phones = context
										.getContentResolver()
										.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
												null,
												ContactsContract.CommonDataKinds.Phone.CONTACT_ID
														+ " = " + contactId,
												null, null);
								while (phones != null && phones.moveToNext()) {
									phoneNumber = Utils.converStandardNumber(phones.getString(phones
											.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
									ContactsWrapper contactsWrapper = new ContactsWrapper(
											contactId, display_name,
											phoneNumber);
									// add to list
									contactsWrappers.add(contactsWrapper);

								}
								phones.close();
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					atm.callbackOnUIThread(onDataListResults, contactsWrappers,
							false);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * TASK READ ALL SMS MESSAGE
	 * 
	 */
	public static void readAllSMS(final Context context,
			final DataRequestCallback<ArrayList<MessageItem>> onDataListResult) {

		final ThreadManager atm = ThreadManager.getInstance(context);

		atm.execute(new Runnable() {

			@Override
			public void run() {
				ArrayList<MessageItem> lstResult = new ArrayList<MessageItem>();
				MessageItem msgItem = null;

				final String SMS_URI_INBOX = "content://sms/inbox";
				// final String SMS_URI_ALL = "content://sms/";
				try {
					Uri uri = Uri.parse(SMS_URI_INBOX);
					String[] projection = new String[] { "DISTINCT address",
							"_id", "thread_id", "body", "date", "type",
							"status", "seen" };
					Cursor cur = context.getContentResolver().query(uri,
							projection,
							"address IS NOT NULL) GROUP BY (address", null,
							null);
					if (cur != null && cur.moveToFirst()) {
						int index_id = cur.getColumnIndex("_id");
						int index_threadid = cur.getColumnIndex("thread_id");
						int index_Address = cur.getColumnIndex("address");
						int index_Body = cur.getColumnIndex("body");
						int index_Date = cur.getColumnIndex("date");
						int index_Type = cur.getColumnIndex("type");
						int index_Status = cur.getColumnIndex("status");
						int index_Seen = cur.getColumnIndex("seen");
						do {
							int id = cur.getInt(index_id);
							long thread_id = cur.getLong(index_threadid);
							String strAddress = Utils.converStandardNumber(cur
									.getString(index_Address));
							String strbody = cur.getString(index_Body);
							long longDate = cur.getLong(index_Date);
							int int_Type = cur.getInt(index_Type);
							int int_Status = cur.getInt(index_Status);
							int int_Seen = cur.getInt(index_Seen);

							if (strAddress != null) {
								// Log.e("int_Seen", int_Seen + "");
								msgItem = new MessageItem(id, thread_id,
										strAddress, "", strbody, longDate,
										int_Type, int_Status, int_Seen);
								lstResult.add(msgItem);
							}

						} while (cur.moveToNext());

						if (!cur.isClosed()) {
							cur.close();
							cur = null;
						}
					}

					atm.callbackOnUIThread(onDataListResult, lstResult, false);

				} catch (SQLiteException ex) {
					ex.printStackTrace();
				}
			}
		});
	}

	/**
	 * TASK READ ALL SMS MESSAGE BY PHONENUMBER
	 * 
	 */
	public static void readAllSMSByPhone(final Context context,
			final String phoneNumber,
			final DataRequestCallback<ArrayList<MessageItem>> onDataListResult) {

		final ThreadManager atm = ThreadManager.getInstance(context);

		atm.execute(new Runnable() {

			@Override
			public void run() {
				ArrayList<MessageItem> lstResult = new ArrayList<MessageItem>();
				MessageItem msgItem = null;

				// final String SMS_URI_INBOX = "content://sms/inbox";
				final String SMS_URI_ALL = "content://sms/";
				try {
					Uri uri = Uri.parse(SMS_URI_ALL);
					String[] projection = new String[] { "_id", "thread_id",
							"address", "body", "date", "type", "status", "seen" };
					Cursor cur = context.getContentResolver().query(uri,
							projection, null, null, null);

					if (cur != null && cur.moveToFirst()) {
						int index_id = cur.getColumnIndex("_id");
						int index_threadid = cur.getColumnIndex("thread_id");
						int index_Address = cur.getColumnIndex("address");
						int index_Body = cur.getColumnIndex("body");
						int index_Date = cur.getColumnIndex("date");
						int index_Type = cur.getColumnIndex("type");
						int index_Status = cur.getColumnIndex("status");
						int index_Seen = cur.getColumnIndex("seen");
						do {
							int id = cur.getInt(index_id);
							long thread_id = cur.getLong(index_threadid);
							String strAddress = Utils.converStandardNumber(cur
									.getString(index_Address));
							String strbody = cur.getString(index_Body);
							long longDate = cur.getLong(index_Date);
							int int_Type = cur.getInt(index_Type);
							int int_Status = cur.getInt(index_Status);
							int int_Seen = cur.getInt(index_Seen);

							if (strAddress != null
									&& strAddress.equals(phoneNumber)) {
								msgItem = new MessageItem(id, thread_id,
										strAddress, "", strbody, longDate,
										int_Type, int_Status, int_Seen);
								lstResult.add(msgItem);

								// Log.e("int_Seen",
								// cur.getInt(cur.getColumnIndex("seen"))
								// + "");
							}
						} while (cur.moveToNext());

						if (!cur.isClosed()) {
							cur.close();
							cur = null;
						}
					}

					atm.callbackOnUIThread(onDataListResult, lstResult, false);

				} catch (SQLiteException ex) {
					ex.printStackTrace();
				}
			}
		});
	}
}
